import 'package:get/get.dart';
import 'package:xiaomishop/app/service/storage.dart';

class GoodSearchController extends GetxController {
  //TODO: Implement GoodSearchController
  String? keyword;

  @override
  void onInit() {
    super.onInit();
    getSearchHistory();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  RxList searchHistorys = [].obs;

  final String KEY_WORDS = "key_words";

  void getSearchHistory() async {
    var historys = await Storage.getData(KEY_WORDS);
    if (historys != null) {
      searchHistorys.value = historys;
    } else {
      searchHistorys.value = [];
    }
    update();
  }

  /**
   * 保存历史记录
   */
  void saveSearchHistory(String keywords) async {
    var historys = await Storage.getData(KEY_WORDS);
    if (historys == null) {
      historys = [];
      historys.add(keywords);
      await Storage.setData(KEY_WORDS, historys);
    } else {
      if (!historys.contains(keywords)) {
        historys.add(keywords);
        await Storage.setData(KEY_WORDS, historys);
      }
    }
  }

  void deleteSearchHistory(String keywords) async {
    List historys = await Storage.getData(KEY_WORDS);
    if (historys.isNotEmpty) {
      historys.remove(keywords);
      await Storage.setData(KEY_WORDS, historys);
      //直接调用searchHistorys.remove即可 不需要 searchHistorys.value.remove
      searchHistorys.remove(keywords);
      update();
    }
  }

  void clearSearchHistory() async {
    await Storage.clear();
    searchHistorys.value.clear();
    searchHistorys.value = [];
    update();
  }
}
